package com.yamanyar.weebill.view.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.yamanyar.weebill.domain.User;
import com.yamanyar.weebill.service.UserService;

/**
 * This converter is spring managed bean due to need of loading the entity with
 * the given id.
 * 
 * Created in Jul 5, 2008.
 * 
 * @author Kaan Yamanyar
 */
@Component("userConverter")
@Scope("request")
public class UserConverter implements Converter {
	private UserService userService;

	@Autowired
	public UserConverter(UserService userService) {
		this.userService = userService;
	}

	public Object getAsObject(FacesContext context, UIComponent component,
			String value) throws ConverterException {
		User user = userService.getUserWithID(new Long(value));
		return user;
	}

	public String getAsString(FacesContext context, UIComponent component,
			Object value) throws ConverterException {
		if (value == null)
			return null;
		User user = (User) value;
		if (user.getId() == null)
			return null;
		return user.getId().toString();
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
